import { observable, action, computed, toJS } from 'mobx';
import { Modal, message, Radio } from 'antd';

const RadioGroup = Radio.Group;
import { WeaTools, WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

export default class DeskTopStore {
    @observable colNum = 7; // 列数固定为7
    @observable state = {
        isSetting: false, // 是否为设置模式
        isSystemer: false, // 是否为维护者
        maxid: 1, // 应用菜单最大id
        datas: [], // 应用菜单列表
        moreDatas: [], // 更多菜单列表
        moreDatasVisible: false,
        rowNum: 3, // 显示行数
        current: 0, // 显示页
        menu_w_h: 0,
        bgImagesVisible: false,
        imgid: '', // 背景图片id
        bgImages: [], // 背景图片列表
        autoCarousel: false, // 是否启用自动轮播
        carouselTime: 3, // 轮播时间
    };
    @observable add_state = {
        visible: false,
        id: '', // 应用菜单id，为空时添加，不为空时编辑
        menuid: '', // 菜单id
        menutype: '1', // 菜单地址类型，1：系统菜单，2：自定义URL
        menuname: '', // 显示名称
        langmenuname: '',
        menuicon: '', // 图标地址
        url: '', // 自定义URL
        unreadapiaddr: '', // 未读数接口地址
        replaceData: [], // 菜单浏览按钮默认值
    };

    constructor() {
        this.getDatas = this.getDatas.bind(this);
        this.setState = this.setState.bind(this);
        this.setAddState = this.setAddState.bind(this);
        this.onAddSave = this.onAddSave.bind(this);
        this.onSave = this.onSave.bind(this);
        this.onSynchronize = this.onSynchronize.bind(this);
        this.onDelete = this.onDelete.bind(this);
        this.deleteToReal = this.deleteToReal.bind(this);
        this.deleteToMore = this.deleteToMore.bind(this);
        this.setColor = this.setColor.bind(this);
        this.addBgImage = this.addBgImage.bind(this);
        this.delBgImage = this.delBgImage.bind(this);
    }


    @computed
    get bgImageObj() {
        const { imgid, bgImages } = this.state;
        const _bgImages = toJS(bgImages);

        let bgImageObj = {};
        for (let i = 0, len = _bgImages.length; i < len; i++) {
            if (_bgImages[i].id == imgid) {
                bgImageObj = { ..._bgImages[i], initialSlide: i };
                break;
            }
        }

        return bgImageObj;
    }

    @action
    getDatas() {
        WeaTools.callApi('/api/portal/desktop/datas', 'POST', {}).then((result) => {
            this.setState(result);
        });
    }

    @action
    setState(state) {
        const _state = Object.assign({}, this.state, state);
        this.state = _state;

        if (state.isSystemer === undefined && (
            state.imgid !== undefined ||
            state.bgImages !== undefined ||
            state.autoCarousel !== undefined ||
            state.carouselTime !== undefined)
        ) {
            const { imgid, bgImages, autoCarousel, carouselTime } = _state;
            WeaTools.callApi('/api/portal/desktop/update', 'POST', {
                imgid,
                bgImages: JSON.stringify(bgImages),
                autoCarousel,
                carouselTime,
            });
        }
    }

    @action
    setState2(state) {
        this.state = Object.assign({}, this.state, state);
    }

    @action
    setAddState(add_state) {
        this.add_state = Object.assign({}, this.add_state, add_state);
    }

    @action
    setColor(color) {
        let bgImages = [...this.state.bgImages];
        let _bgImages = bgImages.map((item) => {
            if (item.id == this.state.imgid) {
                item.color = color;
            }
            return item;
        });
        this.setState({ bgImages: _bgImages });
    }

    @action
    addBgImage(imgsrc) {
        WeaTools.callApi('/api/portal/desktop/addBgImage', 'POST', { imgsrc }).then((result) => {
            if (result.imgsrc) {
                let bgImages = [...this.state.bgImages];
                bgImages.push(result);

                if (this.state.bgImages.length) {
                    this.setState({ bgImages });
                    Modal.confirm({
                        title: getLabel(15172, '系统提示'),
                        content: getLabel(387134, '添加成功，是否替换背景？'),
                        onOk: () => {
                            this.setState({ imgid: result.id });
                        },
                    });
                } else {
                    this.setState({ imgid: result.id, bgImages });
                }
            } else {
                message.error(getLabel(31877, '添加失败！'), 3);
            }
        });
    }

    @action
    delBgImage(params) {
        let _bgImages = toJS(this.state.bgImages);
        let bgImages = [];
        _bgImages.forEach((item) => {
            if (item.id != params.id) {
                bgImages.push(item);
            }
        });

        let imgid = this.state.imgid;
        if (imgid == params.id) {
            if (bgImages.length) {
                imgid = bgImages[0].id;
            } else {
                imgid = '';
            }
        }

        WeaTools.callApi('/api/portal/desktop/delBgImage', 'POST', { ...params, imgid }).then((result) => {
            if (result.api_status == 'success') {
                this.setState({ imgid, bgImages });
                message.success(getLabel(83472, '删除成功！'), 3);
            } else {
                message.error(getLabel(83473, '删除失败！'), 3);
            }
        });
    }

    @action
    onSynchronize(subids) {
        if (subids) {
            this.onSave(subids);
        }
    }

    @action
    onSave(subids) {
        const { datas, moreDatas } = this.state;

        let sortList = [];
        datas.map((item) => {
            sortList.push({ id: item.id, ismore: '0' });
        });
        moreDatas.map((item) => {
            sortList.push({ id: item.id, ismore: '1' });
        });

        WeaTools.callApi('/api/portal/desktop/sortMenuList', 'POST', {
            subids,
            sortList: JSON.stringify(sortList),
        }).then((result) => {
            if (result.api_status == 'success') {
                this.setState({ isSetting: false });
                message.success(`${subids ? getLabel(387135, '同步成功！') : getLabel(83551, '保存成功！')}`, 3);
            } else {
                message.error(`${subids ? getLabel(387136, '同步失败！') : getLabel(84544, '保存失败！')}`, 3);
            }
        });
    }

    @action
    onAddSave() {
        const { id, menuid, menutype, menuname, menuicon, url, unreadapiaddr, replaceData } = this.add_state;
        let isError = false;
        if (menutype == '1') {
            if (!menuid) isError = true;
        } else if (!url.trim()) isError = true;
        if (!menuname.trim()) isError = true;
        if (isError) {
            message.warning(getLabel(15859, '必要信息不完整！'));
            return;
        }

        const updateMenu = () => {
            WeaTools.callApi('/api/portal/desktop/updateMenu', 'POST', {
                id,
                menuid,
                menutype,
                menuname,
                menuicon,
                url,
                unreadapiaddr,
            }).then((result) => {
                if (result.api_status == 'success') {
                    message.success(getLabel(83551, '保存成功！'), 3);
                    this.getDatas();
                    let { isSystemer, maxid } = this.state;
                    let obj = { id, menuid, menutype, menuname, menuicon, url, unreadapiaddr, replaceData };
                    obj.createtype = isSystemer ? 'sys' : 'cus';
                    let datas = [...this.state.datas];
                    if (id) {
                        let index = datas.length;
                        for (let i = 0; i < datas.length; i++) {
                            let item = datas[i];
                            if (item.id == id) {
                                index = i;
                                break;
                            }
                        }
                        datas.splice(index, 1, obj);
                    } else {
                        obj.id = `${maxid + 1}`;
                        datas.push(obj);
                    }
                    this.setState({ maxid, datas });
                    this.setAddState({ visible: false });
                } else {
                    message.error(getLabel(84544, '保存失败！'), 3);
                }
            });
        };

        if (unreadapiaddr) {
            WeaTools.callApi(unreadapiaddr, 'POST').then((result) => {
                if (result.count !== '' && result.count !== null && !isNaN(result.count)) {
                    updateMenu();
                } else {
                    Modal.error({
                        title: getLabel(15172, '系统提示'),
                        content: getLabel(387137, '未读数接口地址返回的数据格式错误！'),
                    });
                }
            }).catch(() => {
                Modal.error({
                    title: getLabel(15172, '系统提示'),
                    content: getLabel(387138, '未读数接口地址不正确！'),
                });
            });
        } else {
            updateMenu();
        }
    }

    @action
    onDelete(index, item) {
        const { isSystemer } = this.state;
        const { createtype } = item;
        if (isSystemer || createtype == 'cus') {
            let deleteType = 1;
            Modal.confirm({
                title: getLabel(15172, '系统提示'),
                content: (
                    <div>
                        <div style={{ height: '30px', lineHeight: '30px', textAlign: 'center' }}>
                            <span>{getLabel(387139, '您是想要将此应用')}</span>
                        </div>
                        <div style={{ height: '30px', lineHeight: '30px', textAlign: 'center' }}>
                            <RadioGroup ecId={`${this && this.props && this.props.ecId || ''}_RadioGroup@r1fcah`} defaultValue={1} onChange={e => deleteType = e.target.value}>
                                <Radio ecId={`${this && this.props && this.props.ecId || ''}_Radio@zipv9a`} key="1" value={1}>{getLabel(387140, '移至更多')}</Radio>
                                <Radio ecId={`${this && this.props && this.props.ecId || ''}_Radio@m0l52l`} key="2" value={2}>{getLabel(81291, '彻底删除')}</Radio>
                            </RadioGroup>
                        </div>
                    </div>
                ),
                onOk: () => {
                    if (deleteType == 1) {
                        this.deleteToMore(index);
                    } else {
                        this.deleteToReal(index);
                    }
                },
            });
        } else {
            this.deleteToMore(index);
        }
    }

    @action
    deleteToReal(index) {
        let datas = [...this.state.datas];
        let deleteDatas = datas.splice(index, 1);
        let id = deleteDatas[0].id;
        WeaTools.callApi('/api/portal/desktop/delMenu', 'POST', { id }).then((result) => {
            if (result.api_status == 'success') {
                message.success(getLabel(83472, '删除成功！'), 3);
                this.setState({ datas });
            } else {
                message.error(getLabel(83473, '删除失败！'), 3);
            }
        });
    }

    @action
    deleteToMore(index) {
        let datas = [...this.state.datas];
        let deleteDatas = datas.splice(index, 1);
        deleteDatas[0].ismore = '1';
        let moreDatas = [...this.state.moreDatas];
        moreDatas.push(deleteDatas[0]);

        let sortList = [];
        datas.map((item) => {
            sortList.push({ id: item.id, ismore: '0' });
        });
        moreDatas.map((item) => {
            sortList.push({ id: item.id, ismore: '1' });
        });

        WeaTools.callApi('/api/portal/desktop/sortMenuList', 'POST', {
            sortList: JSON.stringify(sortList),
        }).then((result) => {
            if (result.api_status == 'success') {
                message.success(getLabel(384404, '移动成功！'), 3);
                this.setState({ datas, moreDatas });
            } else {
                message.error(getLabel(384405, '移动失败！'), 3);
            }
        });
    }
}
